import { createSlice } from '@reduxjs/toolkit';
import { Status } from '../../../type';
import { fetchUser, fetchRandomWall } from './thunk';
import type { UserInfo } from '@/api/user';
import type { Random } from '@/api/home';
// Define a type for the slice state
interface UserState {
  data: UserInfo & { login?: boolean };
  randomWall: Random[];
  loading: boolean;
  status: Status;
  error?: string | null;
}

// Define the initial state using that type
const initialState = {
  data: {},
  randomWall: [],
  loading: false,
  status: Status.IDLE,
} as unknown as UserState;

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    login: state => {
      state.data.login = true;
    },
  },
  extraReducers: builder => {
    builder
      .addCase(fetchUser.pending, state => {
        state.loading = true;
        state.status = Status.LOADING;
        state.error = null;
      })
      .addCase(fetchUser.fulfilled, (state, action) => {
        state.loading = false;
        state.status = Status.SUCCESS;
        state.data = action.payload.data;
      })
      .addCase(fetchUser.rejected, (state, action) => {
        state.loading = false;
        state.status = Status.ERROR;
        state.error = action.payload?.data?.errMsg || action.error.message || 'Unknown error';
      })
      .addCase(fetchRandomWall.pending, state => {
        state.loading = true;
        state.status = Status.LOADING;
        state.error = null;
      })
      .addCase(fetchRandomWall.fulfilled, (state, action) => {
        state.loading = false;
        state.status = Status.SUCCESS;
        state.randomWall = action.payload.data;
      })
      .addCase(fetchRandomWall.rejected, (state, action) => {
        state.loading = false;
        state.status = Status.ERROR;
        state.error = action.payload?.data?.errMsg || action.error.message || 'Unknown error';
      });
  },
});

// Action creators are generated for each case reducer function
export const { login } = userSlice.actions;

export default userSlice.reducer;
